var socket;
var parentObject;

function onOpen()
{
	OutputLog('Socket Status: '+socket.readyState+' (open)');
	var pseudoName = (new Date()).getTime()+"";
	socket.send('0'+pseudoName);
	self.postMessage({"method":"onConnected","data":""});
}

function onClose()
{
	OutputLog('Socket Status: '+socket.readyState+' (Closed)');
	self.postMessage({"method":"onDisconnected","data":""});
}		

function onMessage(msg)
{
	var str = "";
	str = msg.data;
	var id  = str.substr(0, 1);
	var separator = str.indexOf("|");
	var arg1 = "";
	var arg2 = "";
	if(separator != -1)
	{
		arg1 = str.substr(1, separator-1);
		arg2 = str.substr(separator+1);
	}
	else
		arg1 = str.substr(1);				
	
	if(id == "0"){
		OutputLog('Server reply : '+arg1);	
	}
	if(id == "1"){
		OutputLog('Server echo msg : '+arg1);	
	}
	if(id == "2"){
		OutputLog(arg1 + ' said : ' + arg2);	 						
	}
	if(id == "3"){
		//OutputLog(arg1 + ' broadcasted : ' + arg2);
		onDatagram(arg2);
	}
	if(id == "4"){
		//OutputLog('Server streamed : '+arg1);	
		onDatagram(arg1);
	}		
	self.postMessage({"method":"onMessage","data":arg1});
}

function onDatagram(data)
{
	try
	{
		var datagram = eval("("+data+")");
		if(typeof datagram["DatagramType"] != 'undefined')
		{
			if(datagram["DatagramType"] == "INTERACTION")
			{
				self.postMessage({"method":"onInteraction","data":datagram});
			}
			else if(datagram["DatagramType"] == "EVENT")
			{
				self.postMessage({"method":"onEvent","data":datagram});
			}
		}
	}
	catch(e)
	{
	}
}

function OutputLog(msg)
{
	self.postMessage({"method":"onDebug","data":msg});
}

function disconnect(request)
{
	try
	{
		unsuscribeStream(request);
		socket.close();
		OutputLog('Disconnected');
	} 
	catch(exception)
	{
		OutputLog('Error'+exception);
	}
}

function suscribeGroup(request)
{
	socket.send('3subscribe');
}

function suscribeStream(request)
{
	socket.send('4subscribe');
}

function unsuscribeStream(request)
{
	socket.send('4unsubscribe');
}

function connect(request)
{
	try
	{
		socket = new WebSocket(request["url"]);
		OutputLog('Socket Status: '+socket.readyState);
		socket.onopen = onOpen;
		socket.onmessage = onMessage;
		socket.onclose = onClose;		
	} 
	catch(exception)
	{
		OutputLog('Error'+exception);
	}
}

function getClientRequest(event) 
{
	var request = event.data;
	if(request["method"]=="echo")
	{
		OutputLog(request["data"]);
	}
	else if(request["method"]=="connect")
	{
		connect(request);
	}
	else if(request["method"]=="disconnect")
	{
		disconnect(request);
	}
	else if(request["method"]=="suscribeGroup")
	{
		suscribeGroup(request);
	}
	else if(request["method"]=="suscribeStream")
	{
		suscribeStream(request);
	}
	else if(request["method"]=="unsuscribeStream")
	{
		unsuscribeStream(request);
	}
}

self.addEventListener('message', getClientRequest, false);